package com.bookmall.dao;

import com.bookmall.model.Book;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Squking on 2018/5/6.
 */
public class BookDAO {
    private static String SQL_GetAllBook = "SELECT * FROM bookForm";

    public List<Book> getAllBooks() throws Exception {
        ArrayList<Book> listBook = new ArrayList<>();
        PreparedStatement pstmt = null ;
        DBConnection dbc = null ;
        // 下面是针对数据库的具体操作
        try{
            // 连接数据库
            dbc = new DBConnection() ;
            pstmt = dbc.getConnection().prepareStatement(SQL_GetAllBook);
            ResultSet resultSet = pstmt.executeQuery();
            while(resultSet.next()){
//                int id = rs.getInt(1);
//                String name = rs.getString(2);
//                String gender = rs.getString(3);
//                System.out.println("id:"+id+" 姓名："+name+" 性别："+gender);
                Book book = getBookFromResult(resultSet);
                listBook.add(book);
            }
            pstmt.close() ;
        }catch (Exception e){
            throw new Exception("操作出现异常") ;
        }
        finally{
            // 关闭数据库连接
            dbc.close() ;
        }
        return listBook;
    }

    private Book getBookFromResult(ResultSet resultSet)
    {
        Book book = new Book();
        try {
            book.setISBN(resultSet.getString(1));
            book.setPicture(resultSet.getString(2));
            book.setName(resultSet.getString(3));
            book.setAuthor(resultSet.getString(4));
            book.setPrice(resultSet.getInt(5));
            book.setPublish(resultSet.getString(6));
            book.setDescription(resultSet.getString(7));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return book;
    }
}
